package com.ddone.finance.Listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ddone.finance.pojo.dto.DictExcelDto;
import com.ddone.finance.pojo.entity.Dict;
import com.ddone.finance.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ddone
 * @date 2024/4/13-08:48
 */
@Slf4j
public class DictDtoListener extends AnalysisEventListener<DictExcelDto> {

    private DictService dictService;

    private List<DictExcelDto> dictExcelDtos = new ArrayList<>();

    private static final int BATCH_COUNT = 100;

    public DictDtoListener(DictService dictService) {
        this.dictService = dictService;
    }

    @Override
    public void invoke(DictExcelDto data, AnalysisContext context) {
        /*
         * 问题:
         *  1. 批量保存, 需要的参数类型为Dict
         *      将类型 拷贝
         *  2. 如果数据库中已存在Excel中的某个数据字典, 不保存
         */
        dictExcelDtos.add(data);
        if (dictExcelDtos.size() >= BATCH_COUNT) {
            List<Dict> dicts = convertExcelDtos2Dicts();
            dictService.saveBatch(dicts);
            // 存储完成清理 list
            dicts.clear();
        }
    }

    private List<Dict> convertExcelDtos2Dicts() {
        return dictExcelDtos
                .stream()
                .map(excelDto -> {
                    Dict dict = new Dict();
                    BeanUtils.copyProperties(excelDto, dict);
                    return dict;
                })
                .filter(dict -> dictService.count(Wrappers.lambdaQuery(Dict.class).eq(Dict::getId,dict.getId()))==0)
                .collect(Collectors.toList());
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if(dictExcelDtos.size()>0){
            List<Dict> dicts = convertExcelDtos2Dicts();
            //保存到数据库
            dictService.saveBatch(dicts);
            dictExcelDtos.clear();
        }
    }
}
